<template>
	<view class="container">
		<!-- 订单流程图 -->
		<order-flow-chart 
			:order-status="orderData.orderStatus"
			:pay-status="orderData.payStatus"
			:pay-method="orderData.payMethodId"
		></order-flow-chart>
		
		<!-- 订单商品列表 -->
		<view class="order-items-section">
			<!-- 商品 -->
			<view 
				class="item-card" 
				v-for="(item, itemIndex) in orderData.items" 
				:key="itemIndex"
			>
				<image 
					class="item-image" 
					v-if="item.image" 
					:src="item.image" 
					mode="aspectFill"
				></image>
				<image 
					class="item-image" 
					v-else 
					src="../common/images/noImage.png" 
					mode="aspectFill"
				></image>
				<view class="item-info">
					<text class="item-name">{{ item.name }}</text>
					<text class="item-costPrice" v-if="item.costPrice">¥{{ item.costPrice }}</text>
					<view class="item-details">
						<text class="item-price">¥{{ item.price }}</text>
						<text class="item-quantity">x{{ item.quantity }}</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 转账记录上传 -->
		<view class="transfer-record-upload">
			<view class="transfer-record-upload-title">转账记录上传</view>
			<js-uploadfile v-model="image.dataMap" :biz-key="image.id" biz-type="order_transfer_image"></js-uploadfile>
		</view>
		<!-- 订单信息 -->
		<view class="order-info">
			<view class="info-row">
				<text class="info-label">店铺名称</text>
				<text class="info-value">{{ orderData.storeName }}</text>
			</view>
			<!-- 下单人员 -->
			<view class="info-row">
				<text class="info-label">下单人员</text>
				<text class="info-value">{{ orderData.userName }}</text>
			</view>
			<!-- 下单时间 -->
			<view class="info-row">
				<text class="info-label">下单时间</text>
				<text class="info-value">{{ orderData.time }}</text>
			</view>
			<!-- 支付方式 -->
			<view class="info-row">
				<text class="info-label">支付方式</text>
				<text class="info-value">{{ orderData.payMethod }}</text>
			</view>
			<view class="info-row">
				<text class="info-label">总销量</text>
				<text class="info-value">{{ orderData.totalCostPrice }}</text>
			</view>
			<!-- 进货价 -->
			<view class="info-row">
				<text class="info-label">进货价</text>
				<text class="info-value">{{ orderData.totalPrice }}</text>
			</view>
			<!-- 支付状态 -->
			<view class="info-row">
				<text class="info-label">支付状态</text>
				<text class="info-value">{{ orderData.payStatus == 0 ? '未支付' : '已支付' }}</text>
			</view>
			<!-- 订单状态 -->
			<view class="info-row">
				<text class="info-label">订单状态</text>
				<text class="info-value">{{ orderData.status }}</text>
			</view>
			<!-- 收货人 -->
			<view class="info-row">
				<text class="info-label">收货人</text>
				<view class="order-number-container">
					<text class="info-value order-number">{{ orderData.receiverName }}</text>
					<view class="copy-btn" @click="copyText(orderData.receiverName)">
						<text class="copy-text">复制</text>
					</view>
				</view>
			</view>
			<!-- 收货人电话 -->
			<view class="info-row">
				<text class="info-label">收货人电话</text>
				<view class="order-number-container">
					<text class="info-value order-number">{{ orderData.receiverPhone }}</text>
					<view class="copy-btn" @click="copyText(orderData.receiverPhone)">
						<text class="copy-text">复制</text>
					</view>
				</view>
			</view>
			<!-- 收货人地址 -->
			<view class="info-row">
				<text class="info-label">收货人地址</text>
				<view class="order-number-container">
					<text class="info-value order-number">{{ orderData.receiverAddress }}</text>
					<view class="copy-btn" @click="copyText(orderData.receiverAddress)">
						<text class="copy-text">复制</text>
					</view>
				</view>
			</view>
			<!-- 收货日期 -->
			<view class="info-row">
				<text class="info-label">收货日期</text>
				<text class="info-value">{{ orderData.receiveDate }}</text>
			</view>
			<!-- 备注 -->
			<view class="info-row">
				<text class="info-label">备注</text>
				<text class="info-value">{{ orderData.remark }}</text>
			</view>
			<!-- 订单编号 -->
			<view class="info-row">
				<text class="info-label">订单编号</text>
				<view class="order-number-container">
					<text class="info-value order-number">{{ orderData.orderNo }}</text>
					<view class="copy-btn" @click="copyText(orderData.orderNo)">
						<text class="copy-text">复制</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 订单模板弹窗 -->
		<u-popup v-model="showTemplate" mode="center" border-radius="10" width="100%" :mask-close-able="true">
			<view class="template-container">
				<view class="template-header">
					<text class="template-title">销售单</text>
					<text class="template-close" @click="showTemplate = false">✕</text>
				</view>
				<scroll-view class="template-content" scroll-y="true">
					<!-- 公司信息 -->
					<view class="template-company">
						<text class="company-name">{{orderData.storeName || ''}}</text>
					</view>
					
					<!-- 订单基本信息 -->
					<view class="template-order-info">
						<view class="order-info-left">
							<text class="info-item">销售类型: {{ orderData.payMethod || '批发' }}</text>
							<text class="info-item">经手人: {{ orderData.userName || '' }}</text>
							<text class="info-item">单号: {{ orderData.orderNo || '' }}</text>
						</view>
						<view class="order-info-right">
							<text class="info-item">日期: {{ orderData.time || formatDate(new Date()) }}</text>
						</view>
					</view>
					
					<!-- 商品列表 -->
					<view class="template-items">
						<view class="items-header">
							<text class="header-cell">商品</text>
							<text class="header-cell">折后单价</text>
							<text class="header-cell">数量</text>
							<text class="header-cell">单位</text>
							<text class="header-cell">金额</text>
						</view>
						<view 
							class="items-row" 
							v-for="(item, index) in orderData.items" 
							:key="index"
						>
							<text class="cell">{{ item.name }}</text>
							<text class="cell">{{ item.price }}</text>
							<text class="cell">{{ item.quantity }}</text>
							<text class="cell">包</text>
							<text class="cell">{{ (item.price * item.quantity).toFixed(2) }}</text>
						</view>
					</view>
					
					<!-- 合计信息 -->
					<view class="template-summary">
						<!-- 合计行（表格形式，与商品列表对齐） -->
						<view class="summary-total-row">
							<text class="summary-total-cell">合计</text>
							<text class="summary-total-cell"></text>
							<text class="summary-total-cell">{{ getTotalQuantity() }}</text>
							<text class="summary-total-cell"></text>
							<text class="summary-total-cell">{{ orderData.totalPrice || '0.00' }}</text>
						</view>
					</view>

					<!-- 其他信息 -->
					<view class="template-order-info">
						<view class="order-info-left">
							<text class="info-item">总销量: {{ orderData.totalCostPrice || '0.00' }}</text>
							<text class="info-item">支付状态: {{ orderData.payStatus == 0 ? '未支付' : '已支付' }}</text>
							<text class="info-item">订单状态: {{ orderData.status }}</text>
						</view>
						<view class="order-info-right">
							<text class="info-item">收货日期: {{ orderData.receiveDate  }}</text>
							<text class="info-item">备注: {{ orderData.remark  }}</text>
						</view>
					</view>
					
					<!-- 收货人信息 -->
					<view class="template-receiver">
						<text class="receiver-name">{{ orderData.receiverName || '' }}</text>
						<text class="receiver-phone">{{ orderData.receiverPhone || '' }}</text>
						<text class="receiver-address">{{ orderData.receiverAddress || '' }}</text>
					</view>
					
					<!-- 底部提示 -->
					<view class="template-footer">
						<text class="footer-text">收到货后请核对票和品种,有问题及时联系</text>
					</view>
				</scroll-view>
				<!-- <view class="template-actions">
					<view class="template-btn" @click="copyTemplate">复制内容</view>
					<view class="template-btn primary" @click="shareTemplate">分享</view>
				</view> -->
			</view>
		</u-popup>
		
		<!-- 底部操作按钮 -->
		<view class="action-buttons">
			<view class="action-btn secondary" @click="goBack">
				<text class="btn-text">返回</text>
			</view>
			<view class="action-btn primary" @click="showTemplate = true">
				<text class="btn-text">生成模板</text>
			</view>
			<view class="action-btn primary" v-if="orderData.orderStatus == 3 && !isAllOrder" @click="goToConfirmOrder(orderData.items)">
				<text class="btn-text">再来一单</text>
			</view>
			<view class="action-btn primary" v-if="orderData.orderStatus == 2 && orderData.payStatus == 1 && !isAllOrder" @click="updateOrderStatus(orderData.id,3)">
				<text class="btn-text">确认收货</text>
			</view>
			<view class="action-btn primary" v-if="orderData.payStatus == 0 && orderData.orderStatus == 2 && !isAllOrder" @click="goToPay(orderData,false)">
				<text class="btn-text">欠款补交</text>
			</view>
			<view class="action-btn primary" v-if="orderData.orderStatus == 1 && isAllOrder" @click="updateOrderStatus(orderData.id,4)">
				<text class="btn-text">关闭</text>
			</view>
			<view class="action-btn primary" v-if="orderData.orderStatus == 1 && isAllOrder" @click="updateOrderStatus(orderData.id,2)">
				<text class="btn-text">发货</text>
			</view>
			<view class="action-btn primary" v-if="orderData.payStatus == 2 && isAllOrder" @click="goToPay(orderData,true)">
				<text class="btn-text">欠款审核</text>
			</view>
		</view>
	</view>
</template>

<script>
import OrderFlowChart from '@/components/order-flow-chart/order-flow-chart.vue'

export default {
	components: {
		OrderFlowChart
	},
	data() {
		return {
			orderData: {},
			isAllOrder: false,
			showTemplate: false,
			templateContentHeight: 500, // 模板内容区域高度
			image: {
				dataMap:{
					order_transfer_image: '',
					order_transfer_image__del: ''
				},
				id: ''
			}
		}
	},
	onReady() {
		// 计算模板内容区域高度
		const systemInfo = uni.getSystemInfoSync()
		this.templateContentHeight = systemInfo.windowHeight * 0.6
	},
	onLoad(options) {
		// 如果有传入订单ID，可以从API获取订单详情
		if (options.order) {
			let order = JSON.parse(options.order)
			this.orderData = order
			console.log(this.orderData);
			this.image.id = this.orderData.id
		}
		if (options.isAllOrder) {
			this.isAllOrder = true
		}
	},
	methods: {
		// 复制文本
		copyText(text) {
			const copyText = `${text}`
			uni.setClipboardData({
				data: copyText,
				success: () => {
					uni.showToast({
						title: '已复制',
						icon: 'success',
						duration: 1500
					})
				},
				fail: () => {
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 获取总数量
		getTotalQuantity() {
			if (!this.orderData.items || !Array.isArray(this.orderData.items)) {
				return '0.00'
			}
			const total = this.orderData.items.reduce((sum, item) => {
				return sum + (Number(item.quantity) || 0)
			}, 0)
			return total.toFixed(0)
		},
		
		// 格式化日期
		formatDate(date) {
			if (!date) return ''
			const d = new Date(date)
			const year = d.getFullYear()
			const month = String(d.getMonth() + 1).padStart(2, '0')
			const day = String(d.getDate()).padStart(2, '0')
			return `${year}-${month}-${day}`
		},
		
		// 复制模板内容
		copyTemplate() {
			let templateText = `永华智彩\n北京永华团队订票系统\n销售单\n\n`
			templateText += `销售类型: ${this.orderData.payMethod || '批发'}\n`
			templateText += `经手人: ${this.orderData.userName || ''}\n`
			templateText += `单号: ${this.orderData.orderNo || ''}\n`
			templateText += `日期: ${this.orderData.time || this.formatDate(new Date())}\n\n`
			templateText += `商品列表:\n`
			if (this.orderData.items && Array.isArray(this.orderData.items)) {
				this.orderData.items.forEach(item => {
					templateText += `${item.name} - 单价:${item.price} 数量:${item.quantity} 金额:${(item.price * item.quantity).toFixed(2)}\n`
				})
			}
			templateText += `\n合计: ${this.getTotalQuantity()} / ${this.orderData.totalPrice || '0.00'}\n`
			templateText += `应收金额: ${this.orderData.totalPrice || '0.00'}\n`
			templateText += `结算方式: ${this.orderData.payMethod || ''}\n`
			templateText += `实收金额: ${this.orderData.payStatus == 1 ? (this.orderData.totalPrice || '0.00') : '0.00'}\n`
			templateText += `累计欠款: ${this.orderData.payStatus == 0 ? (this.orderData.totalPrice || '0.00') : '0.00'}\n`
			templateText += `备注: ${this.orderData.remark || ''}\n`
			templateText += `送货日期: ${this.orderData.receiveDate || ''}\n\n`
			templateText += `收货人: ${this.orderData.receiverName || ''}\n`
			templateText += `电话: ${this.orderData.receiverPhone || ''}\n`
			templateText += `地址: ${this.orderData.receiverAddress || ''}\n\n`
			templateText += `收到货后请核对票和品种,有问题及时联系`
			
			uni.setClipboardData({
				data: templateText,
				success: () => {
					uni.showToast({
						title: '已复制到剪贴板',
						icon: 'success',
						duration: 1500
					})
				},
				fail: () => {
					uni.showToast({
						title: '复制失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 分享模板
		shareTemplate() {
			// #ifdef MP-WEIXIN
			// 微信小程序分享
			uni.showToast({
				title: '请使用右上角分享',
				icon: 'none'
			})
			// #endif
			
			// #ifdef APP-PLUS
			// APP分享
			plus.share.sendWithSystem({
				type: 'text',
				content: this.getTemplateText()
			})
			// #endif
			
			// #ifdef H5
			// H5分享
			if (navigator.share) {
				navigator.share({
					title: '销售单',
					text: this.getTemplateText()
				}).catch(() => {
					this.copyTemplate()
				})
			} else {
				this.copyTemplate()
			}
			// #endif
		},
		
		// 获取模板文本
		getTemplateText() {
			let templateText = `永华智彩\n北京永华团队订票系统\n销售单\n\n`
			templateText += `销售类型: ${this.orderData.payMethod || '批发'}\n`
			templateText += `经手人: ${this.orderData.userName || ''}\n`
			templateText += `单号: ${this.orderData.orderNo || ''}\n`
			templateText += `日期: ${this.orderData.time || this.formatDate(new Date())}\n\n`
			templateText += `商品列表:\n`
			if (this.orderData.items && Array.isArray(this.orderData.items)) {
				this.orderData.items.forEach(item => {
					templateText += `${item.name} - 单价:${item.price} 数量:${item.quantity} 金额:${(item.price * item.quantity).toFixed(2)}\n`
				})
			}
			templateText += `\n合计: ${this.getTotalQuantity()} / ${this.orderData.totalPrice || '0.00'}\n`
			templateText += `应收金额: ${this.orderData.totalPrice || '0.00'}\n`
			templateText += `结算方式: ${this.orderData.payMethod || ''}\n`
			templateText += `实收金额: ${this.orderData.payStatus == 1 ? (this.orderData.totalPrice || '0.00') : '0.00'}\n`
			templateText += `累计欠款: ${this.orderData.payStatus == 0 ? (this.orderData.totalPrice || '0.00') : '0.00'}\n`
			templateText += `备注: ${this.orderData.remark || ''}\n`
			templateText += `送货日期: ${this.orderData.receiveDate || ''}\n\n`
			templateText += `收货人: ${this.orderData.receiverName || ''}\n`
			templateText += `电话: ${this.orderData.receiverPhone || ''}\n`
			templateText += `地址: ${this.orderData.receiverAddress || ''}\n\n`
			templateText += `收到货后请核对票和品种,有问题及时联系`
			return templateText
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		goToConfirmOrder(items) {
			uni.navigateTo({
				url: '/pages/inventoryManagement/confirmOrder?cart=' + JSON.stringify(items)
			})
		},
		goToPay(order,isAllOrder) {
			uni.navigateTo({
				url: '/pages/inventoryManagement/payDebt?order=' + JSON.stringify(order) + '&isAllOrder=' + isAllOrder
			})
		},
		updateOrderStatus(id,status) {
			// 确定要收货吗
			uni.showModal({
				title: '提示',
				content: status == 4 ? '确定要关闭此订单吗' : (status == 2 ? '确定要发货吗' : '确定要收货吗'),
				success: (res) => {
					if (res.confirm) {
						this.updateOrderStatusToServer(id,status)
					}
				}
			})
		},
		updateOrderStatusToServer(id,status) {
			uni.showLoading({
				title: '操作中...',
				mask: true
			})
			this.$u.api.orderManagement.updateStatus({
				orderNo: id,
				orderStatus: status
			}).then(res => {
				if (res && res.result === 'true') {
					uni.showToast({
						title: '操作成功',
						icon: 'success'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.hideLoading()
					uni.showToast({
						title: res.message || '操作失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('操作失败:', err)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			}).finally(() => {
				uni.hideLoading()
			})
		},
	}
}
</script>

<style scoped>
.container {
	background-color: #ffffff;
	padding-bottom: 100px;
}

/* 订单商品列表 */
.order-items-section {
	padding: 20px;
}

.item-card {
	display: flex;
	align-items: center;
	padding: 15px 0;
	border-bottom: 1px solid #f8f8f8;
}

.item-image {
	width: 60px;
	height: 60px;
	border-radius: 8px;
	margin-right: 15px;
	background-color: #f0f0f0;
}

.item-info {
	flex: 1;
}

.item-name {
	font-size: 14px;
	color: #333333;
	font-weight: bold;
	margin-bottom: 8px;
	display: block;
}

.item-costPrice {
	font-size: 10px;
	color: #666666;
	text-decoration: line-through;
	display: block;
}
.item-details {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.item-price {
	font-size: 14px;
	color: #333333;
	font-weight: bold;
}

.item-quantity {
	font-size: 14px;
	color: #666666;
}

/* 转账记录上传 */
.transfer-record-upload {
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.transfer-record-upload-title {
	font-size: 16px;
	color: #333333;
}
.transfer-record-upload-content {
	font-size: 16px;
	color: #333333;
}
/* 订单信息 */
.order-info {
	padding: 20px;
}

.info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12px 0;
	border-bottom: 1px solid #f8f8f8;
}

.info-row:last-child {
	border-bottom: none;
}

.info-label {
	font-size: 14px;
	color: #666666;
}

.info-value {
	font-size: 14px;
	color: #333333;
}

.order-number-container {
	display: flex;
	align-items: center;
}

.order-number {
	font-size: 12px;
	margin-right: 10px;
}

.copy-btn {
	padding: 4px 8px;
	background-color: #f0f0f0;
	border-radius: 4px;
}

.copy-text {
	font-size: 12px;
	color: #666666;
}

/* 底部操作按钮 */
.action-buttons {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 60px;
	background-color: #ffffff;
	border-top: 1px solid #f0f0f0;
	display: flex;
	padding: 10px 20px;
	gap: 15px;
	z-index: 100;
}

.action-btn {
	flex: 1;
	height: 40px;
	border-radius: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.action-btn.secondary {
	border: 1px solid #333333;
}

.action-btn.primary {
	background-color: #ff4069;
}

.btn-text {
	font-size: 16px;
	font-weight: bold;
}

.action-btn.secondary .btn-text {
	color: #333333;
}

.action-btn.primary .btn-text {
	color: #ffffff;
}

/* 订单模板样式 */
.template-container {
	background-color: #ffffff;
	border-radius: 10px;
	height: 100vh;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.template-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15px 20px;
	border-bottom: 1px solid #f0f0f0;
	flex-shrink: 0;
}

.template-title {
	font-size: 18px;
	font-weight: bold;
	color: #333333;
}

.template-close {
	font-size: 24px;
	color: #999999;
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
}

.template-content {
	flex: 1;
	padding: 5px 10px;
	box-sizing: border-box;
	overflow-y: auto;
	min-height: 0;
}

.template-company {
	text-align: center;
}

.company-name {
	font-size: 18px;
	font-weight: bold;
	color: #000000;
	display: block;
}

.template-order-info {
	display: flex;
	justify-content: space-between;
	margin-bottom: 5px;
	padding: 10px 0;
	border-bottom: 1px dashed #e0e0e0;
}

.order-info-left {
	flex: 1;
}

.order-info-right {
	text-align: right;
}

.info-item {
	font-size: 10px;
	color: #333333;
	display: block;
	margin-bottom: 4px;
}

.template-items {
	margin-bottom:5px;
}

.items-header {
	display: flex;
	background-color: #f5f5f5;
	padding: 10px 5px;
	border-bottom: 1px solid #e0e0e0;
}

.header-cell {
	font-size: 10px;
	color: #333333;
	font-weight: bold;
	flex: 1;
	text-align: center;
}

.items-row {
	display: flex;
	padding: 5px;
	border-bottom: 1px solid #f0f0f0;
}

.cell {
	font-size: 10px;
	color: #333333;
	flex: 1;
	text-align: center;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.template-summary {
	/* margin-bottom: 20px;
	padding-top: 10px; */
	/* border-top: 1px dashed #e0e0e0; */
}

.summary-total-row {
	display: flex;
	align-items: center;
	padding: 5px;
	border-bottom: 1px dashed #e0e0e0;
}

.summary-total-cell {
	font-size: 10px;
	color: #333333;
	font-weight: bold;
	flex: 1;
	text-align: center;
}

.template-receiver {
	text-align: center;
	padding: 5px 0;
	border-bottom: 1px dashed #e0e0e0;
	text-align: left;
}

.receiver-name {
	font-size: 18px;
	font-weight: bold;
	color: #000000;
	display: block;
	margin-bottom: 5px;
}

.receiver-phone {
	font-size: 18px;
	font-weight: bold;
	color: #000000;
	display: block;
	margin-bottom: 5px;
}

.receiver-address {
	font-size: 18px;
	font-weight: bold;
	color: #000000;
	display: block;
}

.template-footer {
	text-align: center;
	padding: 5px 0;
}

.footer-text {
	font-size: 12px;
	color: #666666;
}

.template-actions {
	display: flex;
	gap: 10px;
	padding: 15px 20px;
	border-top: 1px solid #f0f0f0;
	flex-shrink: 0;
}

.template-btn {
	flex: 1;
	height: 40px;
	line-height: 40px;
	text-align: center;
	border-radius: 6px;
	background-color: #f0f0f0;
	color: #333333;
	font-size: 14px;
}

.template-btn.primary {
	background-color: #ff4069;
	color: #ffffff;
}
</style>
